package com.open.capacity.user.service.impl;

import com.open.capacity.common.model.*;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.user.dao.SysRoleDao;
import com.open.capacity.user.dao.TitleDao;
import com.open.capacity.user.service.TitleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Map;

/**
 * 称号实现层
 * @author liutao
 * @date 2021-02-01 16:52
 */
@Service
public class TitleServiceImpl implements TitleService {

    @Autowired
    private TitleDao titleDao;

    @Autowired
    private SysRoleDao sysRoleDao;

    // 模糊查询称号
    @Override
    public PageResult<Title> getSelectTitles(Map<String, Object> params) {
        int count = titleDao.count(params);
        PageUtil.pageParamConver(params,true);
        List<Title> titles = titleDao.getSelectTitles(params);
        return PageResult.<Title>builder().code(0).
                data(titles).count((long) count).build();
    }

    // 添加称号
    @Override
    @Transactional
    public Result addTitle(Title title) {
        boolean isHave = isHaveTitle(title.getTtname());
        if (isHave){
            int result = titleDao.addTitle(title);
            if (result > 0 && title.getTttype() == 1){
                RoleTitle roleTitle = RoleTitle.builder()
                        .titlid(title.getTitlid())
                        .roleid(title.getRoleid()).build();
                int rotlid = titleDao.addRoleTitle(roleTitle);
            }
            return Result.succeed(result == 1?"添加成功":"添加失败");
        }
        return Result.failed("该称号已存在");
    }

    // 修改称号
    @Transactional
    @Override
    public Result updateTitle(Title title) {
        boolean isHaveTitleExceptSelf = isHaveTitleExceptSelf(title.getTtname(), title.getTitlid());
        if (!isHaveTitleExceptSelf){
            int result = titleDao.updateTitle(title);
            titleDao.updateUserTitleByTitleId(title);
            return Result.succeed(result == 1 ? "修改成功" : "修改失败");
        }
        return Result.failed("该称号已存在");
    }

    // 删除称号
    @Transactional
    @Override
    public Result delTitle(int titlid) {
        int result = titleDao.delTitle(titlid);
        return Result.succeed(result > 0?"删除成功":"删除失败");
    }

    @Override
    public PageResult getTitleByUserId(Map<String, Object> params) {
        int count = titleDao.countByUserId(params);
        PageUtil.pageParamConver(params,true);
        List<UserTitle> userTitles = titleDao.getTitleByUserId(params);
        return PageResult.<UserTitle>builder().code(0).
                data(userTitles).count((long) count).build();
    }

    // 判断称号是否存在
    private boolean isHaveTitle(String ttname) {
        List<Title> list = titleDao.isHaveTitle(ttname);
        return list.size() == 0?true:false;
    }

    // 判断称号是否存在
    private boolean isHaveTitleExceptSelf(String ttname, Integer selfTitlid) {
        List<Title> list = titleDao.isHaveTitleExceptSelf(ttname,selfTitlid);
        return list.size() != 0;
    }

    @Transactional
    @Override
    public Result updateTitleOfCoachByUserId(Long userId, Double points) {

        SysRole coach = sysRoleDao.findByCode("COACH");
//        TitleRule coachRule = titleDao.findTitleRuleByRoleIdAndPoints(coach.getId());
        return updateTitleByUserIdAndRoleId(coach.getId(),userId,points,coach.getName());
    }

    @Transactional
    @Override
    public Result updateTitleOfMasterByUserId(Long userId, Double points) {

        SysRole headmaster = sysRoleDao.findByCode("HEADMASTER");
        return updateTitleByUserIdAndRoleId(headmaster.getId(),userId,points,headmaster.getName());
    }


    @Transactional
    @Override
    public Result updateTitleOfStudentByUserId(Long userId, Double points) {

        SysRole headmaster = sysRoleDao.findByCode("STUDENT");
        return updateTitleByUserIdAndRoleId(headmaster.getId(),userId,points,headmaster.getName());
    }

    @Transactional
    @Override
    public Result updateTitleOfRoleCodeByUserId(Long userId, Double points,String roleCode) {
        SysRole headmaster = sysRoleDao.findByCode(roleCode);
        return updateTitleByUserIdAndRoleId(headmaster.getId(),userId,points,headmaster.getName());
    }


    @Override
    public Result getRuleByTypeAndRoleId(Integer typeId,Integer roleId) {
        List<TitleRule> titleRules = titleDao.getRuleByTypeAndRoleId(typeId,roleId);
        return Result.succeed(titleRules,"获取称号类型的规则成功");
    }

    private Result updateTitleByUserIdAndRoleId(Long roleId, Long userId, Double points, String roleName){
        //查询出所有该角色的称号并删除其目前拥有的
        List<Integer> allTitle = titleDao.findTitleByRoleId(roleId);
        for (Integer titleId : allTitle) {
            Integer isHaveThisTitle = titleDao.isHaveThisTitle(titleId,userId);
            if (isHaveThisTitle == 1){
                titleDao.deleteTitleByUserIdAndTitleId(titleId,userId);
            }
        }

        //查询该用户的得分对应的角色专属称号并添加至关系表中
        List<Integer> titleIds = titleDao.findTitleByRoleIdAndPoints(roleId,points);
        Integer addTitleToUser = 0;
        for (Integer titleId : titleIds) {
            addTitleToUser += titleDao.addTitleToUser(userId,titleId);
        }
        if (addTitleToUser == titleIds.size()){
            return Result.succeed("更新"+roleName+"称号成功");
        }
        //手动强制回滚事务，这里一定要第一时间处理
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return Result.failed("更新"+roleName+"称号失败");
    }

    @Transactional
    @Override
    public Result updateTitleByUserIdAndPoints(Long userId, Double points, String typeCode) {
       //查询该code对应类型与points应得的所有称号
        List<Integer> allTitleIds = titleDao.findTitleByTypeCodeAndPoints(typeCode,points);
        Integer updateResult = 0;
        for (Integer titleId : allTitleIds) {
            Integer isHaveThisTitle = titleDao.isHaveThisTitle(titleId,userId);
            if (isHaveThisTitle == 0){
                updateResult += titleDao.addTitleToUser(userId,titleId);
            }else {
                updateResult ++;
            }
        }
        if (updateResult == allTitleIds.size()){
            return Result.succeed("更新typeCode为"+typeCode+"的用户称号成功");
        }
        //手动强制回滚事务，这里一定要第一时间处理
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return Result.failed("更新typeCode为"+typeCode+"的用户称号失败");

    }
}
